//格子背景颜色
function gridbackgroundcolor(num) {
    var gridcolor = '';
    switch (num) {
        case 2:
            gridcolor = '#d36f2c';
            break;
        case 4:
            gridcolor = '#e54d42';
            break;
        case 8:
            gridcolor = '#f37b1d';
            break;
        case 16:
            gridcolor = '#fbbd08';
            break;
        case 32:
            gridcolor = '#8dc63f';
            break;
        case 64:
            gridcolor = '#39b54a';
            break;
        case 128:
            gridcolor = '#1cbbb4';
            break;
        case 256:
            gridcolor = '#0081ff';
            break;
        case 512:
            gridcolor = '#6739b6';
            break;
        case 1024:
            gridcolor = '#9c26b0';
            break;
        case 2048:
            gridcolor = '#e03997';
            break;
        default:
            gridcolor = 'CDC1B4';
            break;

    }

    return gridcolor;
}
//数字颜色
function gridNumColor(num){
    var gridcolor = '';
    switch (num) {
        case 2:
        case 4:
            gridcolor = '#CDC1B4';
            break;
        case 8:
        case 16:
        case 32:
            gridcolor = '#6739b6';
            break;
        case 64:
        case 128:
        case 256:
            gridcolor = '#fbbd08';
            break;
        case 512:
        case 1024:
        case 2048:
            gridcolor = '#0081ff';
            break;
        default:
            gridcolor = '#CDC1B4';
            break;

    }
    return gridcolor;
}

//获取上下左右键值
function keyValues(board) {

    document.onkeydown = function (ev) {

        var e = ev || window.event;

        var keynum = e.which || e.keyCode;

        if (!isGameOver) {
            switch (keynum) {
                case 37:
                    moveGridLeft(board);
                    setTimeout(() => { GetIsGameOver(board); }, 400)

                    break;
                case 38:
                    moveGridUp(board);
                    //gameOver()
                    setTimeout(() => { GetIsGameOver(board); }, 400)
                    break;
                case 39:
                    moveGridRight(board);
                    //gameOver()
                    setTimeout(() => { GetIsGameOver(board); }, 400)
                    break;
                case 40:
                    moveGridDown(board);
                    setTimeout(() => { GetIsGameOver(board); }, 400)
                    break;

            }
        }


    }


}

//监听手指滑动的初始位置
document.addEventListener('touchstart', function (event) {
    startX = event.touches[0].pageX;
    startY = event.touches[0].pageY;
});

//监听手指抬起的位置
document.addEventListener('touchend', function (event) {
    endX = event.changedTouches[0].pageX;
    endY = event.changedTouches[0].pageY;

    var deltaX = endX - startX;
    var deltaY = endY - startY;



    if (!isGameOver) {
        //判断手指滑动是x轴反向还是y轴方向
        if (Math.abs(deltaX) > Math.abs(deltaY)) {

            if (deltaX > 0) {
                //move right
                moveGridRight(board);
                //gameOver()
                setTimeout(() => { GetIsGameOver(board); }, 300)
            }
            else {
                //move left
                moveGridLeft(board);
                setTimeout(() => { GetIsGameOver(board); }, 300)
            }
        }
        else if (Math.abs(deltaX) < Math.abs(deltaY)) {
            if (deltaY > 0) {
                //move down
                moveGridDown(board);
                setTimeout(() => { GetIsGameOver(board); }, 300)
            }
            else {
                //move up
                moveGridUp(board);
                //gameOver()
                setTimeout(() => { GetIsGameOver(board); }, 300)
            }
        }
    }

});




//更新数值格子的位置
function updateNumGrid(board) {


    var node = document.getElementById('container');
    var removenumnode = document.querySelectorAll('.grid-number');

    for (let i = 0; i < removenumnode.length; i++) {

        node.removeChild(removenumnode[i]);

    }

    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {

            if (board[i][j] != 0) {

                var nodeNum = document.createElement('div');

                nodeNum.className = "grid-number";
                nodeNum.id = `grid-number-${i}-${j}`;
                node.appendChild(nodeNum);

                var gridnumnode = document.getElementById(`grid-number-${i}-${j}`);

                var left = cellSpace + j * (cellSideLength + cellSpace);
                var top = cellSpace + i * (cellSideLength + cellSpace);

                gridnumnode.style.width = cellSideLength + 'px';
                gridnumnode.style.lineHeight = cellSideLength + 'px';
                gridnumnode.style.fontSize = (cellSideLength-cellSpace)  / 2 + 'px';

                gridnumnode.style.left = left + "px";
                gridnumnode.style.top = top + "px";
                gridnumnode.innerText = board[i][j];

                gridnumnode.style.backgroundColor = gridbackgroundcolor(board[i][j]);
                gridnumnode.style.color=gridNumColor(board[i][j]);

                if (isCollide[i][j]) {
                    nodeNum.className = "grid-number collide";
                    isCollide[i][j] = false;
                }

            }

        }
    }

    showNum();

    // console.log("是否碰撞" + isCollide);
}

//更新分数
function updateScore() {
    var scoreNode = document.getElementById('score');
    scoreNode.innerText = score;
}

//是否结束游戏
function GetIsGameOver(board) {
    var isWin = false;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] == 2048) {
                isWin = true;
                break;
            }
        }
    }


    if (isWin) {
        var newgrameover = document.createElement('div');
        newgrameover.id = 'gameover';
        newgrameover.innerHTML = '太棒了';
        document.getElementById('container').appendChild(newgrameover);
      
        newgrameover.style.width=containerWidth+'px';
        newgrameover.style.lineHeight=containerWidth+'px';
        newgrameover.style.fontSize=(cellSideLength+cellSpace)/2+'px';

        isGameOver = true;
    }
    else {
        if (!canMove(board) && !isVacancy(board)) {

            var newgrameover = document.createElement('div');
            newgrameover.id = 'gameover';
            newgrameover.innerHTML = 'Game&nbsp;Over';
            document.getElementById('container').appendChild(newgrameover);

            newgrameover.style.width=containerWidth+'px';
            newgrameover.style.lineHeight=containerWidth+'px';
            newgrameover.style.fontSize=(cellSideLength+cellSpace)/2+'px';

            isGameOver = true;
        }
    }



}


//是否可以移动
function canMove(board) {
    if (canMoveLeft(board) || canMoveRight(board) || canMoveTop(board) || canMoveDown(board))
        return true;
    return false;
}

//是否有空缺位置
function isVacancy(board) {
    for (let i = 0; i < 4; i++)
        for (let j = 0; j < 4; j++)
            if (board[i][j] == 0)
                return true;
    return false;
}


//格子向左移动
function moveGridLeft(board) {

    if (canMoveLeft(board)) {

        for (let i = 0; i < 4; i++) {
            for (let j = 1; j < 4; j++) {

                if (board[i][j] != 0) {

                    for (let k = 0; k < j; k++) {

                        if (board[i][k] == 0 && !isRoadblockLeft(i, j, k, board)) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateLeftOrRight(i, j, k);

                            //add
                            board[i][k] = board[i][j];
                            board[i][j] = 0;

                            break;
                        }
                        else if (board[i][k] == board[i][j] && !isRoadblockLeft(i, j, k, board) && !isCollide[i][k]) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateLeftOrRight(i, j, k);

                            //add
                            board[i][k] *= 2;
                            board[i][j] = 0;

                            //当前位置发生碰撞
                            isCollide[i][k] = true;

                            //分数
                            score += board[i][k];
                            updateScore();

                            break;
                        }

                    }

                }
            }
        }

        // console.log(board);
        setTimeout(() => { updateNumGrid(board); }, 320)

    }

}

//是否有障碍物（left）
function isRoadblockLeft(i, j, k, board) {
    for (let index = k + 1; index < j; index++) {
        if (board[i][index] != 0) {
            return true;

        }
    }
    return false;
}


//格子向右移动
function moveGridRight(board) {
    if (canMoveRight(board)) {

        for (let i = 0; i < 4; i++) {

            for (let j = 2; j >= 0; j--) {

                if (board[i][j] != 0) {

                    for (let k = 3; k > j; k--) {

                        if (board[i][k] == 0 && !isRoadblockRight(i, j, k, board)) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateLeftOrRight(i, j, k);

                            board[i][k] = board[i][j];
                            board[i][j] = 0;

                            break;
                        }
                        else if (board[i][k] == board[i][j] && !isRoadblockRight(i, j, k, board) && !isCollide[i][k]) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateLeftOrRight(i, j, k);

                            board[i][k] *= 2;
                            board[i][j] = 0;

                            isCollide[i][k] = true;
                            score += board[i][k];
                            updateScore();

                            break;
                        }

                    }
                }
            }
        }
        setTimeout(() => { updateNumGrid(board); }, 320)
    }

}


//是否有障碍物（right）
function isRoadblockRight(i, j, k, board) {
    for (let index = j + 1; index < k; index++) {
        if (board[i][index] != 0) {
            return true;
        }
    }
    return false;
}


//格子向上移动
function moveGridUp(board) {
    if (canMoveTop(board)) {

        for (let i = 1; i < 4; i++) {

            for (let j = 0; j < 4; j++) {

                if (board[i][j] != 0) {

                    for (let k = 0; k < i; k++) {

                        if (board[k][j] == 0 && !isRoadblockTop(i, j, k, board)) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateTopOrDown(i, j, k);

                            board[k][j] = board[i][j];
                            board[i][j] = 0;

                            break;
                        }
                        else if (board[k][j] == board[i][j] && !isRoadblockTop(i, j, k, board) && !isCollide[k][j]) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateTopOrDown(i, j, k);

                            board[k][j] *= 2;
                            board[i][j] = 0;

                            isCollide[k][j] = true;
                            score += board[k][j];
                            updateScore();

                            break;
                        }

                    }
                }
            }
        }
        setTimeout(() => { updateNumGrid(board); }, 320)
    }

}


//是否有障碍物（top）
function isRoadblockTop(i, j, k, board) {
    for (let index = k + 1; index < i; index++) {
        if (board[index][j] != 0) {
            return true;

        }
    }
    return false;
}


//格子向下移动
function moveGridDown(board) {

    if (canMoveDown(board)) {

        for (let i = 2; i >= 0; i--) {

            for (let j = 0; j < 4; j++) {

                if (board[i][j] != 0) {

                    for (let k = 3; k > i; k--) {

                        if (board[k][j] == 0 && !isRoadblockDown(i, j, k, board)) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateTopOrDown(i, j, k);

                            board[k][j] = board[i][j];
                            board[i][j] = 0;

                            break;
                        }
                        else if (board[k][j] == board[i][j] && !isRoadblockDown(i, j, k, board) && !isCollide[k][j]) {

                            // console.log(i + "," + j + "," + k);
                            //移动动画
                            showMoveAnimateTopOrDown(i, j, k);

                            board[k][j] *= 2;
                            board[i][j] = 0;

                            isCollide[k][j] = true;
                            score += board[k][j];
                            updateScore();

                            break;
                        }

                    }
                }
            }
        }
        setTimeout(() => { updateNumGrid(board); }, 320)
    }

}


//是否有障碍物（down）
function isRoadblockDown(i, j, k, board) {
    for (let index = k - 1; index > i; index--) {
        if (board[index][j] != 0) {
            return true;

        }
    }
    return false;
}


//是否可以向左移动
function canMoveLeft(board) {
    // console.log(board);
    for (let i = 0; i < 4; i++) {
        for (let j = 1; j < 4; j++) {

            if (board[i][j] != 0 && board[i][j - 1] == 0 || board[i][j] != 0 && board[i][j] == board[i][j - 1]) {
                return true;
            }
            else {
                if (i == 3 && j == 3) {
                    return false;
                }
                continue;
            }
        }
    }
}


//是否可以向右移动
function canMoveRight(board) {
    // console.log(board);
    for (var i = 0; i < 4; i++) {
        for (var j = 2; j >= 0; j--) {

            if (board[i][j] == 0) {
                continue;
            }
            else {
                if (board[i][j + 1] == 0 || board[i][j] == board[i][j + 1]) {
                    // alert("可以移动");
                    return true;
                }
            }
        }
    }
    return false;
}

//是否可以向上移动
function canMoveTop(board) {
    for (var i = 1; i < 4; i++) {
        for (var j = 0; j < 4; j++) {

            if (board[i][j] == 0) {
                continue;
            }
            else {
                if (board[i - 1][j] == 0 || board[i][j] == board[i - 1][j]) {
                    // alert("可以移动");
                    return true;
                }
            }
        }
    }
    return false;
}


//是否可以向下移动
function canMoveDown(board) {
    for (var i = 2; i >= 0; i--) {
        for (var j = 0; j < 4; j++) {

            if (board[i][j] == 0) {
                continue;
            }
            else {
                if (board[i + 1][j] == 0 || board[i][j] == board[i + 1][j]) {
                    // alert("可以移动");
                    return true;
                }
            }
        }
    }
    return false;
}



